/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.voto.sunflower.activity.me;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.voto.sunflower.R;
import com.voto.sunflower.SunflowerApplication;
import com.voto.sunflower.activity.BaseActivity;
import com.voto.sunflower.model.request.ModifyPhone;
import com.voto.sunflower.model.response.SmsCode;
import com.voto.sunflower.model.response.UserResponse;
import com.voto.sunflower.retrofit.ClientHttpService;
import com.voto.sunflower.retrofit.NetworkHandler;
import com.voto.sunflower.retrofit.RestError;

/**
 * 注册页
 * 
 */
public class ModifyPhoneActivity extends BaseActivity implements OnClickListener {
	private EditText phoneEditText;
	private EditText smsCodeEditText;
	private EditText passwordEditText;

	private boolean isHide = true;
	private ImageView passwordCtr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_modify_phone);
		
		initComponent();
		initTitle();

	}

	private void initComponent() {
		phoneEditText = (EditText) findViewById(R.id.edit_phone_number);
		smsCodeEditText = (EditText) findViewById(R.id.edit_smsCode);
		passwordEditText = (EditText) findViewById(R.id.edit_password);
		passwordCtr = (ImageView) findViewById(R.id.passwd_ctr);		
		
		// 移动光标到文字后面
//		phoneEditText.setSelection(phoneEditText.getHint().length());
//		smsCodeEditText.setSelection(smsCodeEditText.getHint().length());
//		passwordEditText.setSelection(passwordEditText.getHint().length());
	}

	private void initTitle() {
		TextView back = (TextView) findViewById(R.id.back);
		TextView title = (TextView) findViewById(R.id.title);
		TextView other =(TextView) findViewById(R.id.other);
		
		back.setOnClickListener(this);
		title.setText(R.string.edit_phone);
		other.setVisibility(View.VISIBLE);
		other.setText(getResources().getString(R.string.save));
		other.setOnClickListener(this);
	}

	/**
	 * 获取验证码
	 * 
	 * @param view
	 */
	public void getSmsCode(View view) {
		final String phone = phoneEditText.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			phoneEditText.setError("手机号不能为空");
			phoneEditText.requestFocus();
		} else if (phone.length() < 11 || (!phone.startsWith("1"))) {
			phoneEditText.setError("请输入正确的手机号");
			phoneEditText.requestFocus();
		} else {
			showBlankWaitDialog();
			ClientHttpService.getUserLoginService().getSmsCode(phone, new Callback<SmsCode>() {

				@Override
				public void success(SmsCode arg0, Response arg1) {
					dismissDialog();
					smsCodeEditText.setText(arg0.getmSmsCode());
				}

				@Override
				public void failure(RetrofitError error) {
					dismissDialog();
					if (error.getResponse() != null) {
						int statusCode = error.getResponse().getStatus();
						if (statusCode == 500 || statusCode == 501) {
							final RestError body = (RestError) error.getBodyAs(RestError.class);
							showNetworkErrorDialog(body.errorDetails, null);
						} else if (statusCode == 408) {
							showNetworkErrorDialog(getString(R.string.connect_overtime), null);
						} else {
							showNetworkErrorDialog(error.getMessage(), null);
						}
					}
				}
			});
		}
	}

	/**
	 * 失去焦点
	 */
	public void loseFocus(View view) {
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.requestFocus();
		InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(phoneEditText.getWindowToken(), 0);
	}

	/**
	 * 改变密码状态
	 * 
	 * @param view
	 */
	public void passwdStateChange(View view) {
		if (isHide) {
			isHide = false;
			passwordCtr.setBackgroundResource(R.drawable.show_password);
			passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
		} else {
			isHide = true;
			passwordCtr.setBackgroundResource(R.drawable.hide_password);
			passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
		}
	}

	/**
	 * 完成
	 * 
	 * @param view
	 */
	public void modifyPhoneComplete() {
		final String phone = phoneEditText.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			phoneEditText.setError("手机号不能为空");
			phoneEditText.requestFocus();
			return;
		} else if (TextUtils.isEmpty(smsCodeEditText.getText().toString().trim())) {
			smsCodeEditText.setError("验证码不能为空");
			smsCodeEditText.requestFocus();
			return;
		} else if (TextUtils.isEmpty(passwordEditText.getText().toString().trim())) {
			passwordEditText.setError("密码不能为空");
			passwordEditText.requestFocus();
			return;
		}
		// 修改手机号
		showBlankWaitDialog();
		ModifyPhone modifyPhone = new ModifyPhone();
		modifyPhone.setPhone(phoneEditText.getText().toString().trim());
		modifyPhone.setSmscode(smsCodeEditText.getText().toString().trim());
		modifyPhone.setPassword(passwordEditText.getText().toString().trim());
		ClientHttpService.getMeService().updatePhone(modifyPhone, new UpdatePhoneCallback());
	}

	class UpdatePhoneCallback extends NetworkHandler<UserResponse> {
		@Override
		public void failure(RetrofitError error) {
			super.failure(error);
			dismissDialog();
			
			if (error.getResponse() != null) {
				int statusCode = error.getResponse().getStatus();
				if (statusCode == 500 || statusCode == 501) {
					final RestError body = (RestError) error.getBodyAs(RestError.class);
					showNetworkErrorDialog(body.errorDetails, null);
				} else if (statusCode == 408) {
					showNetworkErrorDialog(getString(R.string.connect_overtime), null);
				} else {
					showNetworkErrorDialog(error.getMessage(), null);
				}
			}
		}

		@Override
		public void success(UserResponse arg0, Response arg1) {
			super.success(arg0, arg1);
			dismissDialog();
			SunflowerApplication.getmUser().setPhone(arg0.getUser().getPhone());
			Toast.makeText(ModifyPhoneActivity.this, R.string.edit_phone_success, Toast.LENGTH_SHORT).show();
			backHandle();
		}
	}

	public void backHandle() {
		InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(phoneEditText.getWindowToken(), 0);
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			backHandle();
			break;
		case R.id.passwd_ctr:
			if (isHide) {
				isHide = false;
				passwordCtr.setBackgroundResource(R.drawable.hide_password);
				passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			} else {
				isHide = true;
				passwordCtr.setBackgroundResource(R.drawable.show_password);
				passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
			}
			break;
		case R.id.other:
			modifyPhoneComplete();
			break;
		default:
			break;
		}
	}

}
